﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
using System.Runtime.Serialization;
using System.Xml.Linq;

namespace GreetingWCFService
{
    public static class GreetingToGreetingDataTranslator
    {
        public static GreetingData GreetingToGreetingData(Greeting greeting)
        {
            GreetingData greetingData = new GreetingData(greeting.GreetingID);            
            greetingData.Message = greeting.Message;
            greetingData.GraphicElements = GraphicElementXmlToGraphicElementData(greeting.GraphicElements);

            return greetingData;
        }

        public static Greeting GreetingDataToGreeting(GreetingData greetingData)
        {
            Greeting greeting = new Greeting();
            greeting.GreetingID = greetingData.GreetingID;
            greeting.Message = greetingData.Message;
            greeting.GraphicElements = GraphicElementDataToGraphicElementXml(greetingData.GraphicElements);

            return greeting;
        }

        private static List<GraphicElementData> GraphicElementXmlToGraphicElementData(XElement xElement)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(GraphicElementData));
            List<GraphicElementData> list = new List<GraphicElementData>();

            foreach (XElement element in xElement.Elements())
            {
                GraphicElementData data = null;

                using (XmlReader reader = element.CreateReader())
                {
                    data = serializer.Deserialize(reader) as GraphicElementData;
                }
                list.Add(data);
            }

            return list;
        }

        private static XElement GraphicElementDataToGraphicElementXml(List<GraphicElementData> list)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(GraphicElementData));
            XElement root = new XElement("GraphicElements");
            XDocument document = new XDocument(root);           

            foreach (GraphicElementData data in list)
            {
                XElement element = SerializeAsXElement(serializer, data);
                root.Add(element);
            }

            return root;
        }        

        private static XElement SerializeAsXElement(XmlSerializer serializer, object obj)
        {
            XDocument document = new XDocument();                          

            using (XmlWriter writer = document.CreateWriter())
            {                
                serializer.Serialize(writer, obj);
            }

            XElement xElement = document.Root;                   
            xElement.Remove();            

            return xElement;
        }        
    }
}
